08. Using Gulp w/ Sass
Using Gulp
Recap: gulp-sass Setup
Why Use Sass?
The main goal of Sass (syntactically awesome stylesheets) is to make it easier to write CSS. Sass "extends" CSS by including features you'd normally see in a typical programming language, such as variables, nesting, functions, and even arithmetic operators. This allows developers to build stylesheets faster!
However, there is one drawback to all this: we need to transpile Sass code in order for your browser to understand it. By transpiling, what we are doing is reproducing the code into another language. There is good news: we can have Gulp take care of all this for us! This is where gulp-sass comes in.
Installation
We first install it locally (i.e., only within that project's folder) with the following command:
npm install gulp-sass
Then, within the same gulpfile.js file, we require it with the following expression:
const sass = require('gulp-sass');
Finally, we create a "styles" task with this code:
gulp.task("styles", function() {
gulp
.src("sass/**/*.scss")
.pipe(sass())
.on("error", sass.logError)
.pipe(gulp.dest("./css"));
});
This creates a new Gulp task that can be run by typing gulp styles in the terminal. Keep in mind that this "styles" task, like our "default" task from earlier, is really just a function!
So what's going on in the code itself? The expression gulp.src('sass/**/*.scss') looks for files with the .scss extension inside the sass folder, as well as inside potential sub-directories. From the .pipe(sass()) part of the code and on, we tell Gulp to run it through Sass (and display errors, if any) before putting the newly-transpiled code into a new CSS file.
Gulp API
For more details regarding Gulp's API (e.g., How does the task() method work? What do I pass into src()?), check out the official documentation.